<template>
  <div class="voice-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">音色管理</h1>
        <p class="page-description">管理和使用您的专属音色，打造我的语音体验</p>
      </div>
      <div class="header-actions">
        <CloneButton @success="handleCloneSuccess" />
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter-section">
      <div class="search-filter-row">
        <div class="filter-tabs">
          <a-button
            :type="selectedType === '' ? 'primary' : 'default'"
            @click="handleTypeChange('')"
            class="filter-tab"
          >
            全部
          </a-button>
          <a-button
            :type="selectedType === '1' ? 'primary' : 'default'"
            @click="handleTypeChange('1')"
            class="filter-tab"
          >
            男声
          </a-button>
          <a-button
            :type="selectedType === '0' ? 'primary' : 'default'"
            @click="handleTypeChange('0')"
            class="filter-tab"
          >
            女声
          </a-button>
        </div>

        <div class="search-container">
          <a-input
            v-model:value="searchKeyword"
            placeholder="搜索音色名称或描述..."
            size="large"
            class="search-input"
            @input="handleSearch($event.target.value)"
          >
            <template #prefix>
              <Search :size="16" />
            </template>
          </a-input>
        </div>
      </div>

      <!-- 音色列表 -->
      <div class="voice-grid">
        <div
          v-for="voice in filteredVoices"
          :key="voice.id"
          class="voice-card"
          :class="{ 'selected': selectedVoice?.id === voice.id }"
          @click="handleSelectVoice(voice)"
        >
          <div class="voice-card-header">
            <div class="voice-info">
              <div class="voice-avatar">
                <Volume2 :size="20" />
              </div>
              <div class="voice-details">
                <h3 class="voice-name">{{ voice.voiceName }}</h3>
                <div class="voice-meta">
                  <span class="voice-type">{{ voice.type === 0 ? '温柔女声' : '磁性男声' }}</span>
                  <span class="voice-status" :class="{ 'available': voice.status === 1 }">
                    {{ voice.status === 1 ? '可用' : '不可用' }}
                  </span>
                </div>
              </div>
            </div>
            <div class="voice-actions">
              <a-button
                type="text"
                size="small"
                @click.stop="handlePlayVoice(voice)"
                :loading="playingVoiceId === voice.id"
                class="play-button"
              >
                <Play v-if="playingVoiceId !== voice.id" :size="16" />
                <Pause v-else :size="16" />
              </a-button>
              <a-button
                type="text"
                size="small"
                class="download-button"
              >
                <Download :size="16" />
              </a-button>
            </div>
          </div>

          <div class="voice-description">
            {{ voice.description || '暂无描述' }}
          </div>

          <div class="voice-card-footer">
            <div class="voice-file-info">
              <span class="voice-duration">时长: 未知</span>
              <span class="voice-file">文件: {{ decodeFileName(voice.voiceFileUrl) }}</span>
            </div>
            <span class="voice-date">
              {{ formatDate(voice.createdAt) }}
            </span>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="filteredVoices.length === 0 && !loading" class="empty-state">
        <div class="empty-icon">
          <Volume2 :size="48" />
        </div>
        <h3>暂无音色</h3>
        <p>您还没有任何音色，点击右上角按钮开始创建吧！</p>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <a-spin size="large" />
        <p>加载中...</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { Volume2, Search, Play, Pause, Download } from 'lucide-vue-next'
import { message } from 'ant-design-vue'
import CloneButton from '@/components/Voice/CloneButton.vue'
import type { VoiceVo, VoicePageSearchDto } from '@/api/generated/data-contracts'
import { Codewin } from '@/api/generated/Codewin'
import { useAuthStore } from '@/stores'

// API实例
const authStore = useAuthStore()
const api = new Codewin({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  securityWorker: () => ({
    headers: authStore.token ? { Authorization: `Bearer ${authStore.token}` } : {}
  })
})

// 数据状态
const loading = ref(false)
const voiceList = ref<VoiceVo[]>([])
const searchKeyword = ref('')
const selectedType = ref('')
const selectedVoice = ref<VoiceVo | null>(null)
const playingVoiceId = ref<string | null>(null)

// 计算属性 - 过滤后的音色列表
const filteredVoices = computed(() => {
  let filtered = voiceList.value

  // 按搜索关键词过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(voice =>
      voice.voiceName?.toLowerCase().includes(keyword) ||
      voice.description?.toLowerCase().includes(keyword)
    )
  }

  // 按类型过滤
  if (selectedType.value !== '') {
    filtered = filtered.filter(voice => voice.type?.toString() === selectedType.value)
  }

  return filtered
})

// 加载音色列表
const loadVoiceList = async () => {
  try {
    loading.value = true

    const response = await api.request({
      path: '/codewin/voice/list',
      method: 'GET',
      query: {
        pageNo: 1,
        pageSize: 100 // 获取所有音色
      },
      headers: authStore.token ? { Authorization: `Bearer ${authStore.token}` } : {},
      secure: true
    })

    if (response.data?.code === 0 && response.data.data) {
      voiceList.value = response.data.data.list || []
    } else {
      message.error(response.data?.message || '获取音色列表失败')
    }
  } catch (error) {
    console.error('获取音色列表失败:', error)
    message.error('获取音色列表失败，请重试')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = (value: string) => {
  searchKeyword.value = value
}

// 类型筛选处理
const handleTypeChange = (value: string) => {
  selectedType.value = value
}

// 选择音色
const handleSelectVoice = (voice: VoiceVo) => {
  selectedVoice.value = voice
}

// 播放音色
const handlePlayVoice = async (voice: VoiceVo) => {
  if (!voice.id) {
    message.error('音色信息不完整')
    return
  }

  try {
    playingVoiceId.value = voice.id

    // 如果有音色文件URL，播放音频
    if (voice.voiceFileUrl) {
      const audio = new Audio(voice.voiceFileUrl)
      audio.play()

      // 播放结束后重置状态
      audio.onended = () => {
        playingVoiceId.value = null
      }

      // 播放错误处理
      audio.onerror = () => {
        playingVoiceId.value = null
        message.error('音频播放失败')
      }
    } else {
      // 获取音色详情
      const response = await api.getVoice(voice.id)
      if (response.data?.code === 0 && response.data.data?.voiceFileUrl) {
        const audio = new Audio(response.data.data.voiceFileUrl)
        audio.play()

        audio.onended = () => {
          playingVoiceId.value = null
        }

        audio.onerror = () => {
          playingVoiceId.value = null
          message.error('音频播放失败')
        }
      } else {
        playingVoiceId.value = null
        message.warning(`音色 "${voice.voiceName}" 暂无音频文件可试听`)
      }
    }
  } catch (error) {
    console.error('播放音色失败:', error)
    playingVoiceId.value = null
    message.error('播放音色失败，请重试')
  }
}

// 克隆成功回调
const handleCloneSuccess = () => {
  loadVoiceList()
  message.success('音色克隆成功！')
}

// 格式化日期
const formatDate = (dateStr?: string) => {
  if (!dateStr) return '-'
  return dateStr.replace('T', ' ').split('.')[0]
}

// 解码文件名
const decodeFileName = (fileUrl?: string) => {
  if (!fileUrl) return '/voices/gentle-female.wav'
  try {
    const fileName = fileUrl.split('/').pop() || ''
    return decodeURIComponent(fileName)
  } catch (error) {
    return fileUrl.split('/').pop() || '/voices/gentle-female.wav'
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadVoiceList()
})
</script>

<style scoped>
.voice-page {
  padding: 24px;
  min-height: 100vh;
  max-width: 1200px;
  margin: 0 auto;

  /* background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); */
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 0;
  padding: 32px 32px 24px 32px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(248, 250, 252, 0.8) 100%);
  /* backdrop-filter: blur(10px); */
  border-radius: 16px 16px 0 0;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-bottom: none;
}

.header-content {
  flex: 1;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 32px;
  font-weight: 700;
  color: #1a1a1a;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-description {
  margin: 0;
  color: #666;
  font-size: 16px;
  line-height: 1.5;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-filter-section {
  margin-bottom: 24px;
  padding: 24px 32px 32px 32px;
  background: #f8f9fa;
  border-radius: 0 0 16px 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.05);
  border: 1px solid #e9ecef;
  border-top: none;
}

.search-filter-row {
  display: flex;
  gap: 24px;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 32px;
}

.filter-tabs {
  display: flex;
  gap: 8px;
}

.filter-tab {
  border-radius: 20px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.filter-tab.ant-btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.search-container {
  flex: 1;
  max-width: 400px;
}

.search-input {
  border-radius: 12px;
  border: 1px solid #e0e0e0;
  transition: all 0.3s ease;
  background: white;
}

.search-input:focus,
.search-input:hover {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

.voice-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
  gap: 24px;
  margin-bottom: 0;
}

.voice-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
  border: 2px solid transparent;
  position: relative;
  overflow: hidden;
}

.voice-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.voice-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.voice-card:hover::before {
  opacity: 1;
}

.voice-card.selected {
  border-color: #667eea;
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.25);
}

.voice-card.selected::before {
  opacity: 1;
}

.voice-card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.voice-info {
  flex: 1;
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.voice-avatar {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  flex-shrink: 0;
}

.voice-details {
  flex: 1;
}

.voice-name {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
  line-height: 1.3;
}

.voice-meta {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.voice-type {
  color: #667eea;
  font-size: 14px;
  font-weight: 500;
}

.voice-status {
  color: #ff4d4f;
  font-size: 14px;
  font-weight: 500;
}

.voice-status.available {
  color: #52c41a;
}

.voice-actions {
  display: flex;
  gap: 8px;
}

.play-button,
.download-button {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.play-button:hover {
  background: rgba(102, 126, 234, 0.1);
  color: #667eea;
}

.download-button:hover {
  background: rgba(102, 126, 234, 0.1);
  color: #667eea;
}

.voice-description {
  color: #666;
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 20px;
  min-height: 44px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.voice-card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.voice-file-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.voice-duration,
.voice-file {
  color: #999;
  font-size: 12px;
}

.voice-file {
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.voice-date {
  color: #999;
  font-size: 12px;
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.empty-icon {
  color: #d9d9d9;
  margin-bottom: 16px;
}

.empty-state h3 {
  margin: 0 0 8px 0;
  color: #666;
  font-size: 18px;
  font-weight: 500;
}

.empty-state p {
  margin: 0;
  color: #999;
  font-size: 14px;
}

.loading-state {
  text-align: center;
  padding: 80px 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.loading-state p {
  margin: 16px 0 0 0;
  color: #666;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .voice-page {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
    padding: 24px;
  }

  .search-filter-row {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .search-container {
    max-width: none;
  }

  .voice-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .page-title {
    font-size: 24px;
  }
}
</style>
